package com.moneywelcome.orderassembly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moneywelcome.exceptions.MwcArgsException;
import com.moneywelcome.orderassembly.model.GoldPrice;
import com.moneywelcome.orderassembly.model.InvestRecord;
import com.moneywelcome.orderassembly.model.UserFinancial;
import com.moneywelcome.orderassembly.mapper.UserFinancialMapper;
import com.moneywelcome.orderassembly.service.ProfitDayService;
import com.moneywelcome.orderassembly.service.UserFinancialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moneywelcome.orderassembly.util.GoldUtil;
import com.moneywelcome.orderfacade.dto.UserFinancialDto;
import com.moneywelcome.orderfacade.vo.OrderPageVo;
import com.moneywelcome.orderfacade.vo.ProfitDayVo;
import com.moneywelcome.orderfacade.vo.UserFinancialVo;
import com.moneywelcome.results.PageResult;
import com.moneywelcome.results.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户持仓表 服务实现类
 * </p>
 *
 * @author alice
 * @since 2022-01-06
 */
@Service
public class UserFinancialServiceImpl extends ServiceImpl<UserFinancialMapper, UserFinancial> implements UserFinancialService {
    @Autowired
    private ProfitDayService pds;
    @Override
    public UserFinancialDto create(UserFinancialVo userFinancialVo) {
        UserFinancial financial = BeanUtil.copyProperties(userFinancialVo, UserFinancial.class);
        save(financial);
        return BeanUtil.copyProperties(financial,UserFinancialDto.class);
    }
    @Override
    public UserFinancialDto updateShares(Long financialId, Double shares) {
        UserFinancial financial = getOne(new QueryWrapper<UserFinancial>().eq("financial_id", financialId));
        if(null==financial) throw new MwcArgsException( "持仓不存在",StatusCode.Error);
        Double share = financial.getFinancialShares() + shares;
        if(share<0) throw new MwcArgsException("份额不足",StatusCode.Error);
        financial.setFinancialShares(share);
        if (!saveOrUpdate(financial)) throw new MwcArgsException("更新份额失败",StatusCode.Error);
        return BeanUtil.copyProperties(financial,UserFinancialDto.class);
    }
    @Override
    public void updateRevenue() throws IOException {
        List<UserFinancial> financials = list();
        HashMap<Integer, GoldPrice> map = new HashMap<>();
        GoldPrice goldPrice=null;
        if(null==financials||financials.size()==0) throw new MwcArgsException("持仓记录不存在",StatusCode.Error);
        for (UserFinancial financial : financials) {
            if (map.containsKey(financial.getGoldId())) {//获取黄金实时价格
                goldPrice  = map.get(financial.getGoldId());
            } else {
                goldPrice = GoldUtil.getCurrentPrice(String.valueOf(financial.getGoldId()));
                map.put(financial.getGoldId(),goldPrice);
            }
            //计算收益
            Double revenue = financial.getFinancialShares() * (goldPrice.getLastPrice() - goldPrice.getYesyPrice());
            revenue = (double) Math.round(revenue * 100) / 100;
            //扣除管理费
            System.out.println(financial);
            revenue=revenue*(1-financial.getManageRate()/365);

            financial.setHoldRevenue(financial.getHoldRevenue()+revenue);
            financial.setTotalRevenue(financial.getTotalRevenue()+revenue);
            //更新每日收益记录
            ProfitDayVo profitDayVo = new ProfitDayVo();
            profitDayVo.setUserId(financial.getUserId());
            profitDayVo.setFinancialId(financial.getFinancialId());
            profitDayVo.setCurrentProfit(revenue);
            pds.create(profitDayVo);
        }
        if (!saveOrUpdateBatch(financials)) throw new MwcArgsException("更新收益失败",StatusCode.Error);
    }
    @Override
    public PageResult<UserFinancialDto> financialQuery(OrderPageVo op) {
        QueryWrapper<UserFinancial> qw = new QueryWrapper<>();
        if (null!= op.getUserId())  qw.eq("user_id", op.getUserId());
        String keyword = op.getKeyword();
        if (!StrUtil.hasEmpty(keyword)) qw.like("variety",keyword);
        Page<UserFinancial> page = page(new Page<>(op.getCurrent(), op.getSize()), qw);
        PageResult pageResult = BeanUtil.copyProperties(page, PageResult.class);
        pageResult.setData(BeanUtil.copyToList(page.getRecords(), UserFinancialDto.class));
        pageResult.setTotalCount(page.getTotal());
        return pageResult;
    }
}
